﻿using AutoMapper;
using MachineVision.Domain;
using MachineVision.Service.Dto;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;

namespace MachineVision.Service
{
    public partial class TokenService : ITokenService
    {
        private readonly VisionDbContext context;
        private readonly IMapper mapper;

        public TokenService(VisionDbContext context, IMapper mapper)
        {
            this.mapper = mapper;
            this.context = context;
        }


        public Token_YunMou GetTokenFromDB()
        {
            if(context.Tokens_YunMou.Any())
                return context.Tokens_YunMou.OrderByDescending(s => s.CreateTime).FirstOrDefault();
            return null;
        }

        public bool SetToken(string Token,DateTime EXTime)
        {

            context.Tokens_YunMou.Add(new Token_YunMou
            {
                AccessToken = Token,
                ExpirationTime = EXTime,
                CreateTime = DateTime.Now,
            });
            int a = context.SaveChanges();
            return a > 0;

        }


        public Token_YunMou GetTokenFromURL(string token_url, string client_id, string client_secret)
        {
            Dictionary<string, string> paramsparams = new Dictionary<string, string>();
            paramsparams.Add("client_id", client_id);
            paramsparams.Add("client_secret", client_secret);
            paramsparams.Add("grant_type", "client_credentials");
            string result = HttpXmlClient.Post(token_url, paramsparams, null);
            if (string.IsNullOrEmpty(result))
            {
                throw new Exception("无法获取token");
            }
            JObject jo = (JObject)JsonConvert.DeserializeObject(result);

            return new Token_YunMou {
                AccessToken = jo["access_token"].ToString(),
                ExpirationTime = DateTime.Now.AddSeconds((int)jo["expires_in"]),
            };
        }

        public string GetVideo(string video_url,string accessToken, string deviceSerial, int channelNo, string protocol)
        {
            Dictionary<string, string> headers = new Dictionary<string, string>();
            headers.Add("Accept", "application/json");
            headers.Add("Authorization", String.Format("Bearer {0}", accessToken));


            YMVideo yMVideo = new YMVideo();
            yMVideo.deviceSerial = deviceSerial;
            yMVideo.channelNo = channelNo;
            yMVideo.protocol = protocol;
            string str = JsonConvert.SerializeObject(yMVideo);

            string result  = HttpXmlClient.Post(video_url, str, headers);


            JObject jo = (JObject)JsonConvert.DeserializeObject(result);
            return jo["data"] != null ? jo["data"]["url"].ToString() : jo["message"].ToString();
        }


        public string GetUIKit(string uikit_url, string accessToken, string deviceSerial, int channelNo)
        {

            Dictionary<string, string> headers = new Dictionary<string, string>();
            headers.Add("Accept", "application/json");
            headers.Add("Authorization", String.Format("Bearer {0}", accessToken));

            string result = HttpXmlClient.GetHttpResponse(uikit_url, headers);
            JObject jo = (JObject)JsonConvert.DeserializeObject(result);
            if (jo["data"] == null)
            {
                return jo["message"].ToString();
            }
            else {
                string url = $"https://open.ys7.com/ezopen/h5/iframe_se?url=ezopen://open.ys7.com/{deviceSerial}/{channelNo}.live&accessToken={jo["data"]["token"]}";//ra.19ooh7t66mjv3uux7hmocu2t78u0i582-8oitmy9e8q-133elza-5rkffsywa";
                return url;// jo["data"] != null ? jo["data"]["token"].ToString() : jo["message"].ToString();
            }
        }

        public string GetVideoHistory(string history_url, string accessToken, string deviceSerial, int channelNo, string protocol,int type ,string start ,string end)
        {
            Dictionary<string, string> headers = new Dictionary<string, string>();
            headers.Add("Accept", "application/json");
            headers.Add("Authorization", String.Format("Bearer {0}", accessToken));


            YMVideo yMVideo = new YMVideo();
            yMVideo.deviceSerial = deviceSerial;
            yMVideo.channelNo = channelNo;
            yMVideo.protocol = protocol;
            yMVideo.type = type;
            yMVideo.startTime = start;
            yMVideo.stopTime = end;
            string str = JsonConvert.SerializeObject(yMVideo);

            string result = HttpXmlClient.Post(history_url, str, headers);


            JObject jo = (JObject)JsonConvert.DeserializeObject(result);
            return jo["data"] != null ? jo["data"]["url"].ToString() : jo["message"].ToString();
        }
    }

    public class YMVideo
    {
        /// <summary>
        /// 设备序列号
        /// </summary>
        public string deviceSerial { get; set; }
        /// <summary>
        /// 通道号，非必选，默认为1
        /// </summary>
        public int channelNo { get; set; }
        /// <summary>
        /// 流播放协议，2-hls、3-rtmp、4-flv，默认为1
        /// </summary>
        public string protocol { get; set; }
        /// <summary>
        /// 	视频清晰度，1-高清（主码流）、2-流畅（子码流）
        /// </summary>
        public int quality { get; set; } = 2;
        /// <summary>
        /// 类型，1-预览，2-本地录像回放，3-云存储录像回放，非必选，默认为1
        /// </summary>
        public int type { get; set; } = 1;

        public string startTime { get; set; }
        public string stopTime { get; set; }
    }
}